#!/bin/env python
#-*- coding:utf-8 -*-
import sys , os 
import time
import socket , select 


class Config:
	def __init__( self , lip = u"0.0.0.0" , lnm = u"255.255.255.0" , \
				wip = u"0.0.0.0", wnm = u"255.255.255.0" , \
				ssid = None , channel = -1 , space = u"" ):
		self._config = {}
		self._config["lip"] = lip
		self._config["lnm"] = lnm
		self._config["wip"] = wip
		self._config["wnm"] = wnm
		self._config["ssid"] = ssid
		self._config["channel"] = channel
		self._config["space"] = space

	def cutSsid( self , Ssid = self._config["ssid"]):
		if Ssid:
			return []
		tempArray = []
		ansArray = []
		Ssid = Ssid.strip()
		tempArray = Ssid.split["_"]
		tempArray = [ x[1:]  for x in tempArray[1:]]
		return tempArray
	
	def updateSsid( self , newSsid ):
		if newSsid == "" or newSsid == self._config["ssid"]: 
			return -1
		newSsidArray = self.cutSsid( newSsid )
		nowSsidArray = self.cutSsid()
		
		if self._config["ssid"]:
			if newSsidArray[1] > nowSsidArray[1]:
				self._config["ssid"] = u"NODE_I%s_V%s_C%s"%( nowSsidArray[0] , newSsidArray[1] , nowSsidArray[2] )
		else:
			self._config["ssid"] = newSsid
		return 1

	def updateSpace( self ):
		try:
			fDfInfo = os.popen( "df" )
		except Exception , e:
			print str(e)
		tempDfInfo = fDfInfo.read().strip()
		tempArray = tempDfInfo.splitlines()
		tempArray = tempArray[1].split(" ")
		tempArray = [ x for x in tempArray if x != "" and x != " "]
		self._config["space"] = tempArray[1]

class Client():
	def __init__( self , confPath  = "/www/conf/test" ):
		self._clientConf = Config()
		self._confFilePath = confPath
		self._apConf = Config()

	def getWifiNode( self ):
		tempNodeInfo = ""
		try:
			fIwlistInfo = os.popen("awk -f awkfile temp")
		except Exception, e:
			raise e
			return ()
		tempNodeInfo = fIwlistInfo.read()
		if tempNodeInfo == "NULL" or tempNodeInfo =="":
			return ()
		tempArray = tempNodeInfo.split("\t")
		return ( tempArray[0] , tempArray[2] )

	def checkUsb( self ):
		return 1

	def checkConfFile( self ):
		if self._confFilePath == "":
			return -1
		if not os.path.isfile(self._confFilePath) :
			return -1
		return 1

	def getConf( self ):
		fConf = open(self._confFilePath , "r")
		tempIp = ""
		#tempIp = fConf.readline().strip()
		tempIp = "110"
		self._clientConf._config["lip"] = "192.168.2." + unicode(int(tempIp)+1)
		self._clientConf._config["lnm"] = "255.255.255.0"
		self._clientConf._config["wip"] = "192.168.2." + unicode(int(tempIp)+2)
		self._clientConf._config["wnm"] = "255.255.255.0"
		self._apConf._config["lip"] = "192.168.2." + tempIp
		self._apConf._config["lnm"] = "255.255.255.0"
		fConf.close()
		print self._clientConf._config
		return 1

	def wputConf( self ):
		tempStr = "wput --tries=2 --timeout=10 --waitretry=3 %s \
ftp://network:123@192.168.2.111%s"%( self._confFilePath , self._confFilePath)
		print tempStr
		return 1

	def write2network( self ):
		if os.path.isfile("/etc/config/network") == False:
			return -1
		fNetwork = open("/etc/config/network" , "w");
		strNetwork = "\
config interface 'loopback'\n\
	option ifname   'lo'\n\
	option proto    'static'\n\
	option ipaddr   '127.0.0.1'\n\
	option netmask  '255.0.0.0'\n\
config interface 'lan'\n\
	option ifname   'eth0'\n\
	option type     'bridge'\n\
	option proto    'static'\n\
	option ipaddr   '%s'\n\
	option netmask  '%s'\n\
config interface 'wwan'\n\
	option proto    'static'\n\
	option ipaddr   '%s'\n\
	option netmask  '%s'\n\
config interface 'stabridge'\n\
        option proto    'relay'\n\
        option network  'lan wwan'\n"%( self._clientConf._config["lip"] , self._clientConf._config["lnm"] ,\
					 self._clientConf._config["wip"] , self._clientConf._config["wnm"] ) 
		fNetwork.write(strNetwork)
		fNetwork.close()
		return 1

	def write2wireless( self ):
		if not os.path.isfile("/etc/config/wireless"):
			return -1
		fWireless = open("/etc/config/wireless" , "w");
		self._clientConf._config["channel"] = 1
		self._clientConf._config["ssid"] = "818"
		strWireless = "\
config wifi-device  radio0\n\
        option type     mac80211\n\
        option channel  %s\n\
        option macaddr  38:83:45:3F:3D:1A\n\
        option hwmode   11ng\n\
        option htmode   HT20\n\
        list ht_capab   SHORT-GI-20\n\
        list ht_capab   SHORT-GI-40\n\
        list ht_capab   RX-STBC1\n\
        list ht_capab   DSSS_CCK-40\n\
        # REMOVE THIS LINE TO ENABLE WIFI:\n\
        # option disabled 1\n\
config wifi-iface\n\
        option device   radio0\n\
        option network  wwan\n\
        option mode     sta\n\
        option ssid     %s\n\
        option encryption psk\n\
        option key      hahah818\n"%( self._clientConf._config["channel"] , self._clientConf._config["ssid"] )
		fWireless.write( strWireless )
		fWireless.close()
		return 1

	def socketclient( self ):
		try:
			sock = socket.socket( socket.AF_INET , socket.SOCK_STREAM )  
			sock.connect( ( self._apConf._config["lip"] , 50000 ) )
			sock.setblocking( False )
		except Exception, e:
			return -1
		i = 0
		j = 0
		while i < 5:
			print "i" , i
			while j < 5:
				print "j" , j
				try:
					readable , writeable , exceptionable = select.select( [ sock , ] , [ sock , ] , [ ] , 20 ) 
				except Exception, e:
					continue
				for write in writeable:
					try:
						wifiNode = self.getWifiNode()
						tempStr = ""
						if wifiNode and ( self._clientConf._config["ssid"] != wifiNode[1] ):
							tempStr = "SSID:%s\t"%( wifiNode[1] )
							self._clientConf._config["ssid"] = wifiNode[1]
							self._clientConf._config["channel"] = wifiNode[0]
						else: 
							tempStr = "_1_"
						try:
							write.send( tempStr )
						except Exception , e:
							print str(e)
							continue
						print "send to server" , tempStr
					except Exception, e:
						continue
				for read in readable:
					tempStr = ""
					try:
						tempStr= read.recv( 4096 )
						if tempStr  != "":
							i = 0
							j = 0
							if tempStr .find( "ok" ) != -1:
								pass
								if self.write2wireless() == 1:
									#os.system("wifi down;wifi on")
						print "Receive info" , buf
					except Exception, e:
						continue
				time.sleep(1)
				i += 1
				j += 1
		sock.close()
		return -1

	def run( self ):
		while 1:
			if self.checkUsb() != 1 or self.checkConfFile() != 1:
				continue
			if self.getConf() != 1:
				continue
			if self.wputConf() != 1:
				continue
			if self.write2network() != 1:
				continue
			if self.write2wireless() != 1:
				continue
			os.system("/etc/init.d/network restart")
			self.socketclient()

if __name__ == '__main__':
	cl = Client("/www/conf/test")
	cl.run()
